<template>
    <div class="login">
        <navbar/>
        <div class="container">
            <login-form :submit="submitForm" :button-disabled="buttonDisabled"/>
        </div>
        <document-title title="Login"/>
    </div>
</template>

<script>
	/* eslint-disable no-undef */

	import Navbar from './layout/Index/Navbar';
	import LoginForm from './layout/Index/LoginForm';
	import DocumentTitle from 'vue-fiu-ui/src/main/js/components/widget/DocumentTitle';

	export default {
		components: {
			DocumentTitle,
			LoginForm,
			Navbar
		},
		name: 'login',
		data () {
			return {
				buttonDisabled: false
			};
		},
		methods: {
			submitForm (data) {
				axios.post('/auth/token', this.getRequestData(data), {}).then(res => {
					this.setLoginData(res.data);
				});
			},
			getRequestData (data) {
				let params = {};
				params.grant_type = 'password';
				params.client_id = this.$key.CLIENT_ID;
				params.client_secret = this.$key.CLIENT_SECRET;
				params.username = data.email;
				params.password = data.password;
				return params;
			},
			setLoginData (data) {
				this.$storage.clear();
				this.$storage.set(this.$key.ACCESS_TOKEN, data.access_token);
				this.$storage.set(this.$key.REFRESH_TOKEN, data.refresh_token);
				this.$storage.set(this.$key.EXPIRES_IN, (new Date().getTime() + (data.expires_in * 1000)));
				this.getUserInfo();
			},
			getUserInfo () {
				axios.get('/user').then(res => {
					if (res.data.success === false) return this.$notify.error(res.data.data);
					this.$storage.set(this.$key.USER_DATA, this.$compile.compileStr(JSON.stringify(res.data.data)));
					this.$router.push({name: 'Index'});
				});
			}
		}
	};
</script>

<style scoped>

</style>
